package com.kd.service.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kd.dao.EmployeeMapper;
import com.kd.entity.Customer;
import com.kd.entity.Employee;
import com.kd.service.employee.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class EmployeeTokenServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeTokenService {
    @Autowired
    private EmployeeService employeeService;

    @Override
    public String getToken(Employee user) {
        String token="";
        token= JWT.create().withAudience(String.valueOf(user.getEid()))
                .sign(Algorithm.HMAC256(user.getPassword()));

        return token;
    }
    public Employee getCurrentUser(HttpServletRequest request) {
        // 从请求头获取Token（注意与拦截器中的header key保持一致）
        String token = request.getHeader("token");  // 不是"Authorization"，因为拦截器中用的是"token"

        if (token == null || token.isEmpty())  {
            return null;
        }

        try {
            // 解码Token获取eid（与拦截器中的逻辑一致）
            String eid = JWT.decode(token).getAudience().get(0);

            // 查询员工信息
            Employee employee = employeeService.findEmployeeByEId(eid);
            if (employee == null) {
                return null;
            }

            // 验证Token有效性（与拦截器中的验证逻辑一致）
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(employee.getPassword())).build();
            verifier.verify(token);  // 如果验证失败会抛出异常

            return employee;
        } catch (JWTVerificationException e) {
            // Token解析或验证失败
            return null;
        }
    }

}
